import React, { useState, useEffect } from 'react';
import {
  message,
  Form,
  Input,
  InputNumber,
  Row,
  Col,
  TreeSelect,
  Drawer,
  Button,
  Radio,
  Checkbox,
} from 'antd';
import { CaretRightOutlined, CaretDownOutlined } from '@ant-design/icons';

import { upadataRule, addRule, getRuleDetail } from '@/services/ant-design-pro/api';
import { getMenu } from '../../MenuList/api';
import styles from '../index.less';

const UpdateForm = props => {
  // 结构化数据
  const { visible, onCancel, onSuccess, data, type, currentIndex = 0 } = props;

  // 初始化 form
  const [form] = Form.useForm();
  const [tvalue, setTValue] = useState([]);
  const [loading, setLoading] = useState(false);

  const [treeData, setTreeData] = useState(false);

  const getDetail = () => {
    getRuleDetail(data.roleId).then(res => {
      if (res.code === 0) {
        const menuIds = res.data.menuIds || [];
        setTValue(menuIds);
        form.setFieldsValue({ ...res.data, status: res.data.status * 1 || 0 });
      } else {
        message.error(res.msg || '获取详情失败');
      }
    });
  };

  /**
   * @zh-CN 加载菜单
   *  */

  const setList = arr => {
    const newTreeData = [];
    arr.map(res => {
      const obj = {
        title: res.menuName,
        value: res.menuId,
        key: res.menuId,
        parentId: res.parentId,
      };

      if (res.children && res.children.length) {
        obj.children = setList(res.children);
      }
      newTreeData.push(obj);
      return '';
    });
    return newTreeData;
  };

  const getMenuList = () => {
    getMenu().then(res => {
      if (res.code === 0 && res.data && res.data.length) {
        setTreeData(setList(res.data));
        //loops(setList(res.data));
      } else {
        message.error(res.msg || '菜单加载失败');
      }
    });
  };

  useEffect(() => {
    if (!treeData && visible) {
      getMenuList();
    }
    if (type === 'updata' && visible === true) {
      getDetail();
    } else {
      form.resetFields();
      setTValue([]);
    }
    form.setFieldsValue({ roleSort: currentIndex, status: 0 });
  }, [visible]);

  // 栅格化
  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 },
  };

  // ---------------------------------------------- new tree ---------------------------------

  const clickDown = citem => {
    const newList = JSON.parse(JSON.stringify(treeData));
    const setList = list => {
      list.map(item => {
        if (citem.key === item.key && !item.down) {
          item.down = true;
          if (item.children && item.children.length) {
            setList(item.children);
          }
        } else if (citem.key === item.key && item.down) {
          item.down = false;
        } else {
          if (item.children && item.children.length) {
            setList(item.children);
          }
        }
      });
    };
    setList(newList);
    setTreeData(newList);
  };

  const setChange = (arr, e, citem) => {
    console.log('arr=', arr, 'citem=', citem);
    arr &&
      arr.length &&
      arr.map(item => {
        if (citem.key === item.key || citem === 'children') {
          item.checked = e.target.checked;
          if (item.children && item.children.length) {
            setChange(item.children, e, 'children');
          }
        } else {
          setChange(item.children, e, citem);
        }
      });
    return arr;
  };

  const onChangeMenu = (e, citem) => {
    const newList = JSON.parse(JSON.stringify(treeData));
    const list = setChange(newList, e, citem);
    setTreeData(list);
  };

  const setNewTree = t => {
    return (
      <>
        <div></div>
        <>
          {t &&
            t.length &&
            t.map(item => {
              return (
                <div key={item.key}>
                  {item.children && item.children.length && (
                    <span onClick={() => clickDown(item)}>
                      {item.down === true ? <CaretRightOutlined /> : <CaretDownOutlined />}
                    </span>
                  )}
                  <Checkbox
                    key={item.key}
                    checked={item.checked}
                    parentId={item.parentId}
                    onChange={e => onChangeMenu(e, item)}
                  >
                    {item.title}
                  </Checkbox>
                  <div
                    style={{ paddingLeft: 30, display: `${item.down === true ? 'block' : 'none'}` }}
                  >
                    {item.children?.length && setNewTree(item.children)}
                  </div>
                </div>
              );
            })}
        </>
      </>
    );
  };

  // -------------------------------------------------------- end ------------------------------------
  // 填充字段数据

  const { SHOW_ALL } = TreeSelect;
  const { SHOW_CHILD } = TreeSelect;
  const treeDataChange = value => {
    setTValue(value);
  };

  const tProps = {
    treeData,
    value: tvalue,
    onChange: (value, info, extra) => {
      treeDataChange(value);
    },
    // onCheck: (value, info) => {
    //   console.log('value', value);
    //   console.log('info', info);
    // },
    treeCheckable: true,
    // treeCheckStrictly: true,
    showCheckedStrategy: SHOW_ALL,
    placeholder: '',
    style: {
      width: '100%',
    },
  };

  /**
   * @en-US Update node
   * @zh-CN values
   *
   * @param fields
   */
  const updataData = values => {
    const hide = message.loading('正在添加');
    setLoading(true);

    upadataRule({
      ...values,
      roleId: data.roleId,
      menuIds: tvalue,
    }).then(res => {
      hide();
      setLoading(false);
      if (res.code === 0) {
        onCancel(false);
        onSuccess();
      } else {
        message.error(res.msg || '修改失败，请重试');
      }
    });
  };
  /**
   * @en-US Update node
   * @zh-CN 添加
   *
   * @param values
   */
  const addData = values => {
    const hide = message.loading('正在添加');
    setLoading(true);
    addRule({ ...values, menuIds: tvalue }).then(res => {
      hide();
      setLoading(false);
      if (res.code === 0) {
        onCancel(false);
        onSuccess();
      } else {
        message.error(res.msg || '添加失败，请重试');
      }
    });
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param values
   */
  const sendData = () => {
    form.validateFields().then(values => {
      if (type === 'updata') updataData(values);
      if (type === 'add') addData(values);
    });
  };

  const modelClose = () => {
    onCancel(false);
  };

  return (
    <>
      <Drawer
        getContainer={false}
        width={640}
        title={type === 'updata' ? '修改' : '添加'}
        visible={visible}
        onClose={modelClose}
        maskClosable={false}
        footer={
          <div
            style={{
              textAlign: 'right',
            }}
          >
            <Button onClick={modelClose} style={{ marginRight: 10 }}>
              取消
            </Button>
            <Button onClick={sendData} type="primary" loading={loading} disabled={loading}>
              保存
            </Button>
          </div>
        }
      >
        <div>{setNewTree(treeData)}</div>
        <Form {...formItemLayout} name="control-ref" form={form}>
          <Form.Item label="角色名称" name="roleName" rules={[{ required: true }]}>
            <Input maxLength={20} allowClear />
          </Form.Item>
          <Form.Item label="角色字符串" name="roleKey" rules={[{ required: true }]}>
            <Input maxLength={20} allowClear />
          </Form.Item>
          <Form.Item width="xs" name="roleSort" label="显示顺序" rules={[{ required: true }]}>
            <InputNumber min={0} max={1000} />
          </Form.Item>
          <div className={styles.treeBox}>
            <Row>
              <Col span={14} push={4}>
                <TreeSelect {...tProps} showSearch multiple treeDefaultExpandAll allowClear />
              </Col>
              <Col span={4} pull={14}>
                <div className={styles.treeName}>选择菜单：</div>
              </Col>
            </Row>
          </div>
          <Form.Item name="status" label="状态">
            <Radio.Group>
              <Radio value={0}>正常</Radio>
              <Radio value={1}>停用</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="备注" name="remark">
            <Input.TextArea maxLength={200} allowClear />
          </Form.Item>
        </Form>
      </Drawer>
    </>
  );
};

export default UpdateForm;
